//
//  WiFiInfo.m
//  SulitLoan
//
//  Created by 虞嘉伟 on 2025/3/12.
//


#import "WiFiInfo.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import <NetworkExtension/NetworkExtension.h>


@interface WiFiInfo ()
@property (nonatomic, strong) CLLocationManager *locationManager;
@end

@implementation WiFiInfo

+ (instancetype)shared {
    static WiFiInfo *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [WiFiInfo new];
    });
    return instance;
}

- (void)getWiFiInfo:(void(^)(NSString *ssid, NSString *bssid))completion {
    if (self.ssid.length && self.bssid.length) {
        !completion ?: completion(self.ssid, self.bssid);
        return;
    }
    if (@available(iOS 14.0, *)) {
        CLLocationManager *locationManager = [CLLocationManager new];
        self.locationManager = locationManager;
        // 向用户申请临时开启一次精确位置权限
        [locationManager requestTemporaryFullAccuracyAuthorizationWithPurposeKey:@"WantsToGetWiFiSSID"];
        // iOS 14及以上版本
        [NEHotspotNetwork fetchCurrentWithCompletionHandler:^(NEHotspotNetwork * _Nullable currentNetwork) {
            if (currentNetwork) {
                self.ssid = currentNetwork.SSID;
                self.bssid = currentNetwork.BSSID;
                NSLog(@"SSID: %@, BSSID: %@", self.ssid, self.bssid);
            } else {
                NSLog(@"未连接到Wi-Fi");
            }
            !completion ?: completion(self.ssid, self.bssid);
        }];
    } else {
        // iOS 14以下版本
        NSArray *interfaces = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
        for (NSString *interface in interfaces) {
            NSDictionary *networkInfo = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)interface);
            if (networkInfo) {
                self.ssid = networkInfo[(__bridge NSString *)kCNNetworkInfoKeySSID];
                self.bssid = networkInfo[(__bridge NSString *)kCNNetworkInfoKeyBSSID];
                !completion ?: completion(self.ssid, self.bssid);
                NSLog(@"SSID: %@, BSSID: %@", self.ssid, self.bssid);
                break;
            }
        }
    }
}

@end
